package cn.kuick.deal.alert.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import java.io.*;
import java.util.*;

/**
 读取配置文件，只能解析jsondoc.version=1.0格式的键值对，能过滤#注释的内容。
 默认配置文件没有语法错误
 配置文件=左边的是key，右边的是value，拿到的值会消除所有空格。
 */
public class ReadAndWriteConfigFile {
    private static final Log log = LogFactory.getLog(ReadAndWriteConfigFile.class);

    public static Map readConfigInfo(String filePath){
        File file = new File(filePath);
        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("配置文件不存在或路径有误。");
        }

        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        Map map = new HashMap();
        try {
            String lineStr = null;
            while ((lineStr = bufferedReader.readLine()) !=null){
                if(!isEffectiveContent(lineStr)){
                    continue;
                }

                String[] keyAndValue = lineStr.split("=");

                keyAndValue[0] = keyAndValue[0].replaceAll(" ", "");
                keyAndValue[1] = keyAndValue[1].replaceAll(" ", "");
                map.put(keyAndValue[0], keyAndValue[1]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fileInputStream.close();
            inputStreamReader.close();
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return map;
    }

    public static void writeConfigInfo(String filePath, List<String> list){
        File file = new File(filePath);

        try {
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            for(int i = 0; i<list.size(); i++){
                bufferedWriter.write(list.get(i));
                bufferedWriter.newLine();
            }

            bufferedWriter.flush();
            fileWriter.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static boolean isEffectiveContent(String lineStr){
        if(lineStr.isEmpty()){
            return false;
        }
        if(lineStr.charAt(0) == '#'){
            return false;
        }

        return true;
    }
}
